package training;

/**
 * @Author liangzai
 * @Description:
 */
public class J25_6_2_Training {
    //分发糖果
    public int candy(int[] ratings) {
        int len = ratings.length;
        if(len == 1){
            return 1;
        }
        int[] pre_nums = new int[len];
        //计算前缀的数值
        pre_nums[0] = ratings[0]>ratings[1] ? 2 : 1;
        for(int i=1; i<len; i++){
            if(ratings[i]>ratings[i-1]){
                pre_nums[i] = pre_nums[i-1]+1;
            }
            else{
                pre_nums[i] = 1;
            }
        }
        //计算后缀的数值
        int[] lst_nums = new int[len];
        lst_nums[len-1] = lst_nums[len-1]>lst_nums[len-2] ? 2 : 1;
        for(int i=len-2; i>=0; i--){
            if(ratings[i] > ratings[i+1]){
                lst_nums[i] = lst_nums[i+1]+1;
            }
            else{
                lst_nums[i] = 1;
            }
        }
        //根据前缀数值与后缀数值，选取最大的，即是当前小孩所应当得到的糖果数
        int[] nums = new int[len];
        for(int i=0; i<len; i++){
            nums[i] = Math.max(pre_nums[i], lst_nums[i]);
        }
        //求总和返回
        int sum = 0;
        for(int i=0; i<len; i++){
            sum+=nums[i];
        }
        return sum;
    }
}
